package com.momoc.mrpc.rpc.handler;

import com.momoc.mrpc.register.RegisterContext;
import com.momoc.mrpc.register.definition.MRpcRegDefinition;
import com.momoc.mrpc.rpc.message.MRpcRequestMessage;
import com.momoc.mrpc.rpc.message.MRpcResponseMessage;
import com.momoc.mrpc.util.SpringContextUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.springframework.stereotype.Component;

/**
 * @author momoc
 * @version 1.0
 * @className MRpcRequestHandler
 * @description 处理请求入站
 * @date 2022/7/25 4:54 下午
 */
@ChannelHandler.Sharable
public class MRpcRequestHandler extends SimpleChannelInboundHandler<MRpcRequestMessage> {


    Random random = new Random();
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MRpcRequestMessage msg)  {
        Map<String, MRpcRegDefinition> rpcNameServiceMap = RegisterContext.getRpcNameServiceMap();
        //取服务
        MRpcRegDefinition mRpcRegDefinition = rpcNameServiceMap.get(msg.getInterfaceName());
        Class interfaceClass = mRpcRegDefinition.getInterfaceClass();
        Object bean = SpringContextUtil.getBean(interfaceClass);

        String methodName = msg.getMethodName();
        Method method = null;
        MRpcResponseMessage mRpcResponseMessage = new MRpcResponseMessage();
        try {
            method = interfaceClass.getMethod(methodName, msg.getParameterTypes());
            Object invoke = method.invoke(bean, msg.getParameterValue());
            mRpcResponseMessage.setSequenceId(msg.getSequenceId());
            mRpcResponseMessage.setData(invoke);
        } catch (Exception e) {
            mRpcResponseMessage.setException(new RuntimeException("远程调用出错：" + e.getCause().getMessage()));
            e.printStackTrace();
        }finally {
            ctx.writeAndFlush(mRpcResponseMessage);
        }
    }
}
